package ltd.dujiabao.activemq.queue;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.jms.*;
import java.io.IOException;

/**
 * @author : DuJiabao
 * @Project : active-mq
 * @Time : 2021/5/4 18:45
 * @Desc :
 */
public class QueueConsumer {
  private static final String ACTIVEMQ_URL = "tcp://192.168.233.134:61616";  // 服务器端口号，地址
  //private static final String ACTIVEMQ_URL = "tcp://127.0.0.1:61616";  // 服务器端口号，地址
  private static final String DESTINATION_NAME = "queue01";  // 目的地名称
  private ActiveMQConnectionFactory activeMQConnectionFactory;
  private Connection connection = null;
  private Session session = null;
  private MessageConsumer consumer = null;

  @Before
  public void before() throws JMSException {
    activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
    connection = activeMQConnectionFactory.createConnection();
    connection.start();  // 开启连接
    session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);// 不使用事务，使用自动签收
  }

  /**
   * 同步方法接收
   * @throws JMSException
   */
  @Test
  public void test1() throws JMSException {
    Queue queue = session.createQueue(DESTINATION_NAME);  // 目的地
    consumer = session.createConsumer(queue);   // 消费者
    // 监听，3s超时
    while (true) {
      // 接受一个消息，并将消息转换为Text类型的消息
      TextMessage message = (TextMessage) consumer.receive(3000L);  // 定制超时时间3s
      //TextMessage message = (TextMessage) consumer.receive();    // 没有超时时间
      if (null != message) System.out.println(message.getText());
      else break;
    }
  }

  /**
   * 异步方法接收
   * @throws JMSException
   * @throws IOException
   */
  @Test
  public void test2() throws JMSException, IOException {
    consumer = session.createConsumer(session.createQueue(DESTINATION_NAME));
    consumer.setMessageListener((message) -> {
      if (message instanceof TextMessage) {
        TextMessage textMessage = (TextMessage) message;
        try {
          System.out.println("接收到一个消息：" + textMessage.getText());
        } catch (JMSException e) {
          e.printStackTrace();
        }
      }
    });
    System.in.read();
  }


  @After
  public void after() throws JMSException {
    consumer.close();
    session.close();
    connection.close();
    System.out.println("关闭");
  }
}
